package com.comleader.baseproject.web.controller;

import com.comleader.baseproject.common.bean.response.ResponseCodeEnum;
import com.comleader.baseproject.common.bean.response.ResponseResult;
import com.comleader.baseproject.common.exception.ExceptionCast;
import com.comleader.baseproject.domain.Demo;
import com.comleader.baseproject.service.DemoService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张志航
 * @description 用户登录接口类，包含用户管理
 * swaggerui的地址：http://localhost:8080/swagger-ui.html#/demo-controller
 * @date 2020-11-25 09:55
 * method(Param param1.Param param2)：method description
 * dateToTimestmap(Date date)： 将时间转换为时间戳的方法
 * datetimeToString(Date date)：将时间类转换为格式化的字符串
 */
@RequestMapping("/demo")
@RestController
@Api(value = "DemoController", tags = {"演示接口"}, description = "演示用的一些接口")
public class DemoController {

    @Autowired
    private DemoService loginUserService;

    // 查询类示例,@ApiImplicitParams代表参数集合， @ApiImplicitParam是具体的参数内容，name参数名，value参数说明，required是否可空，dataType类型，example示例
    @ApiOperation(value = "查询类示例", notes = "查询类示例", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "String", example = "1"),
    })
    @ApiResponses(@ApiResponse(code = 200, message = "success", response = ResponseResult.class))
    @GetMapping("/getDemoById/{id}")
    public ResponseResult<Demo> getDemoById(@PathVariable("id") String id) {
        if (StringUtils.isEmpty(id)) {
            // 进行参数校验
            // 空值校验统一采用ResponseCodeEnum.INVALIDPARAM枚举抛出空值异常，由ExceptionCatch类统一处理
            ExceptionCast.cast(ResponseCodeEnum.INVALIDPARAM);
        }
        // 调用Service查询用户信息
        Demo demo = loginUserService.selectById(id);
        // 封装返回结果
        ResponseResult responseResult = ResponseResult.SUCCESS(demo);
        return responseResult;
    }


    @GetMapping("/getDemoByName/{name}")
    public ResponseResult<Map<String, List<Demo>>> getDemoByName(@PathVariable("name") String name) {
        // 进行参数校验
        if (StringUtils.isEmpty(name)) {
            // 空值校验统一采用ResponseCodeEnum.INVALIDPARAM枚举抛出空值异常，由ExceptionCatch类统一处理
            ExceptionCast.cast(ResponseCodeEnum.INVALIDPARAM);
        }
        // 调用Service查询用户信息
        List<Demo> demos = loginUserService.selectByName(name);
        // 封装返回结果
        Map<String, List> listMap = new HashMap<>();
        listMap.put(name,demos);
        ResponseResult responseResult = ResponseResult.SUCCESS(listMap);
        return responseResult;
    }

    @PostMapping("/addDemo")
    public ResponseResult addDemo(@RequestBody Demo demo) {
        if (demo == null) {
            // 进行空值校验
            ExceptionCast.cast(ResponseCodeEnum.INVALIDPARAM);
        }
        ResponseResult responseResult = loginUserService.add(demo);
        return responseResult;
    }

    @PutMapping("/updateDemo")
    public ResponseResult updateDemo(@RequestBody Demo demo) {
        if (demo == null) {
            // 进行空值校验
            // 参数异常校验统一采用ResponseCodeEnum.INVALIDPARAM枚举抛出空值异常，由ExceptionCatch类统一处理
            ExceptionCast.cast(ResponseCodeEnum.INVALIDPARAM);
        }
        ResponseResult responseResult = loginUserService.update(demo);

        return responseResult;
    }

    @DeleteMapping("/deleteDemoById/{id}")
    public ResponseResult deleteDemoById(@PathVariable("id") String id) {

        return ResponseResult.SUCCESS();
    }

    /**
     * 导出文件的方法,以流式导出，前端可以以wondow.open("url")的方式来打开新窗口下载文件
     *
     * @param response
     */
    @ApiOperation(value = "下载文件示例", notes = "下载文件示例", produces = "application/json")
    @GetMapping("/exportMethod")
    public void exportMethod(HttpServletResponse response) {
        try (OutputStream outputStream = response.getOutputStream();
             BufferedOutputStream bos = new BufferedOutputStream(outputStream)) { // 这种方式声明的流运行后会自动关闭

            // 文件名，以UTF-8格式编码
            String fileName = new String(("filename.txt").getBytes("UTF-8"), "ISO-8859-1");
            //相应内容编码
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/format-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            bos.write("hahaha".getBytes("UTF-8")); // 响应的内容写入到response中
            bos.flush(); //刷新
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
